package com.hd.sup.config.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.hd.sup.config.rabbitmq.MqQueueConstant;
import com.hd.sup.modules.alarm.model.AlarmReport;
import com.hd.sup.modules.alarm.service.IAlarmReportService;
import com.hd.sup.modules.vehicle.model.VehicleEndPos;
import com.hd.sup.modules.vehicle.service.IVehicleEndPosService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * @author chentl
 * @version V1.0
 * @Project 交通运输第三方监测平台
 * @Title RabbitConsumer.java
 * @Description rabbitMQ 消费者
 * @Package com.hd.determine.config.rabbitmq.consumer
 * @date 2021/1/6 3:36 下午
 * @Copyright: 深圳市宏电技术股份有限公司 All rights reserved.
 */
@Slf4j
@Component
public class RabbitConsumer {

    @Resource
    private IVehicleEndPosService vehicleEndPosService;
    @Resource
    private IAlarmReportService alarmReportService;

    /**
     * @return void
     * @author chentl
     * @description 静态数据同步队列
     * @date 2021/1/13 5:26 下午
     * @params [msg, channel]
     */
    @RabbitListener(queues = MqQueueConstant.STATIC_DATA_SYNC_QUEUE)
    @RabbitHandler
    public void staticDataQueue(Message msg, Channel channel) throws IOException {
        String message = new String(msg.getBody());

        channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
        try {
            VehicleEndPos data = JSON.parseObject(message, VehicleEndPos.class);

            vehicleEndPosService.syncUnCompletionData(data);


        } catch (Exception e) {
            //丢弃这条消息
            channel.basicNack(msg.getMessageProperties().getDeliveryTag(), false, false);
            log.error("[rabbit] 静态数据同步队列发生异常", e);
            log.error("[rabbit] 异常原始消息: {}", message);
        }
    }

    /**
     * @return void
     * @author chentl
     * @description 分析报告处理队列
     * @date 2021/3/2 9:04 上午
     * @params [msg, channel]
     */
    @RabbitListener(queues = MqQueueConstant.REPORT_DATA_GEN_QUEUE)
    @RabbitHandler
    public void reportDataQueue(Message msg, Channel channel) throws IOException {
        String id = new String(msg.getBody());
        log.info("[rabbit] 分析报告处理队列接收到消息:{}", id);
        try {

            alarmReportService.fillReportData(id);

            log.info("[rabbit] 分析报告处理队列任务执行结束");
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //丢弃这条消息
            channel.basicNack(msg.getMessageProperties().getDeliveryTag(), false, false);
            log.error("[rabbit] 分析报告处理队列发生异常", e);
            log.error("[rabbit] 异常原始消息: {}", id);
        }
    }

}
